package com.mjlf.akka.simple;

import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.dispatch.OnSuccess;
import akka.pattern.Patterns;
import akka.util.Timeout;
import scala.concurrent.Future;
import scala.util.Try;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName AckDemo
 * @auther mjlf
 * @Date 2019/8/5 10:10
 * @Description 联系Akka的同步消息发送
 */
public class AckDemo {

    static class AckActor extends AbstractActor{

        //创建消息接收处理器
        @Override
        public Receive createReceive() {
            return receiveBuilder().matchAny(msg -> {
                //打印接收到信息
                System.out.println("接收到的消息是 : " + msg);
                //睡眠1秒，永远验证消息同步Ack
                Thread.sleep(1000);
                //返回消息
                getSender().tell("我收到了你的消息:"+msg, getSelf());
            }).build();
        }
    }

    public static void main(String[] args) {
        ActorSystem system = ActorSystem.create();
        ActorRef ackActorRef = system.actorOf(Props.create(AckActor.class), "ackActorRef");

        //创建超时时间工具
        Timeout timeout = new Timeout(2, TimeUnit.SECONDS);

        //使用future接收ack消息
        Future<Object> future = Patterns.ask(ackActorRef, "akka ask test", timeout);

        //future当完成时， 成功会做什么
        future.onComplete(new OnSuccess<Try<Object>>() {
            @Override
            public void onSuccess(Try<Object> result) throws Throwable {
                //成功出来逻辑
                System.out.println(result.get());
            }
        }, system.dispatcher());

        System.out.println("ack succeed");
    }
}
